﻿using Learun.Util.SqlSugar;
using Learun.Util;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using DbType = System.Data.DbType;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-06-21 15:32
    /// 描 述：关联类型表
    /// </summary>
    public class ec_CableSetService
    {
        #region 仓储
        Repository<ec_projectEntity> _projectRepository => new Repository<ec_projectEntity>();
        Repository<ec_CableSetEntity> _cableSetRepository => new Repository<ec_CableSetEntity>();
        #endregion
        #region 获取数据
        /// <summary>
        /// 获取列表数据
        /// <summary>
        /// <returns></returns>
        public IEnumerable<ec_CableSetEntity> GetList(string ProjId, string CableId)
        {
            try
            {
                var ProjectEntity = new ec_projectEntity();
                //参考写法
                //var queryParam = queryJson.ToJObject();
                //var strSql = new StringBuilder();
                //strSql.Append(@"SELECT t.* ");
                if (string.IsNullOrEmpty(ProjId))
                {
                    return null;
                }
                else
                {
                    ProjectEntity = _projectRepository.GetById(ProjId);
                    //strSql.Append($"  FROM ec_cable_set_{ProjectEntity.ProjectIndex} t ");
                    var Res = SqlSugarHelper.Db.Queryable<ec_CableSetEntity>().AS("ec_cable_set_" + ProjectEntity.ProjectIndex)
                        //.InnerJoinIF<ec_CableEntity>(!string.IsNullOrEmpty(CableId), (a, b) => a.CableID == b.CableID).AS<ec_CableEntity>("ec_cable_" + ProjectEntity.ProjectIndex)
                        .WhereIF(!string.IsNullOrEmpty(CableId), a => a.CableID == CableId)
                        .OrderBy(a => a.CableSetSeq)
                        .ToList();
                    return Res;
                }
                //strSql.Append(" WHERE 1=1 ");
                //// 虚拟参数
                ////var dp = new DynamicParameters(new { });
                //var dp = new List<SugarParameter>();
                //if (!queryParam["CableID"].IsEmpty())
                //{
                //    dp.Add(new SugarParameter("CableID", queryParam["CableID"].ToString(), DbType.String));
                //    strSql.Append(" AND t.CableID = @CableID ");
                //}
                //strSql.Append(" order by t.CableSetSeq ");
                ////return this.BaseRepository().FindList<ec_CableSetEntity>(strSql.ToString(), dp);
                //return SqlSugarHelper.Db.SqlQueryable<ec_CableSetEntity>(strSql.ToString()).AddParameters(dp).ToList();

            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }


        #endregion

        #region 提交数据
        /// <summary>
        /// 删除实体数据
        /// <param name="ProjectId">主键</param>
        /// <param name="CableSetID">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string ProjectId, string CableSetID)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                var tableName = ProjectSugar.TableName<ec_CableSetEntity>(ProjectId);
                var wireTableName = ProjectSugar.TableName<ec_CableSetWireEntity>(ProjectId);

                SqlSugarHelper.Db.Deleteable<ec_CableSetEntity>(x => x.CableSetID == CableSetID).AS(tableName).ExecuteCommand();
                SqlSugarHelper.Db.Deleteable<ec_CableSetWireEntity>(x => x.CableSetID == CableSetID).AS(wireTableName).ExecuteCommand();

                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string ProjectId, string keyValue, ec_CableSetEntity entity, out String NewID)
        {
            try
            {
                NewID = "0";
                var ProjectEntity = new ec_projectEntity();
                if (!string.IsNullOrWhiteSpace(ProjectId))
                {
                    //ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(ProjectId);
                    ProjectEntity = _projectRepository.GetById(ProjectId);
                }
                else
                {
                    return;
                }

                if (!string.IsNullOrEmpty(keyValue))
                {

                    entity.Modify(keyValue);
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        //this.BaseRepository().Update(entity);
                        _cableSetRepository.Update(entity);
                    }
                    else
                    {
                        //this.BaseRepository().UpdateByNoMap(entity, $"ec_Cable_set_{ProjectEntity.ProjectIndex}", "CableSetID");
                        _cableSetRepository.AsUpdateable(entity).AS($"ec_Cable_set_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }

                    NewID = keyValue;
                }
                else
                {
                    entity.Create();
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        //this.BaseRepository().Insert(entity);
                        _cableSetRepository.Insert(entity);
                    }
                    else
                    {
                        //this.BaseRepository().InsertByNoMap(entity, $"ec_Cable_set_{ProjectEntity.ProjectIndex}");
                        _cableSetRepository.AsInsertable(entity).AS($"ec_Cable_set_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }
                    NewID = entity.CableSetID;
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存某个特定的属性（随着connection）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntityByConnections(string ProjectId, string keyValue, string SetName)
        {
            try
            {
                var ProjectEntity = new ec_projectEntity();
                if (!string.IsNullOrWhiteSpace(ProjectId))
                {
                    //ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(ProjectId);
                    ProjectEntity = _projectRepository.GetById(ProjectId);
                }
                else
                {
                    return;
                }


                //var db = this.BaseRepository().BeginTrans();

                //db.ExecuteBySql($@" update ec_Cable_set_{ProjectEntity.ProjectIndex} set cablesetname='{SetName}' WHERE cablesetid ='{keyValue}'; ");

                //db.Commit();
                _cableSetRepository.AsTenant().BeginTran();
                SqlSugarHelper.Db.Ado.ExecuteCommand($@" update ec_Cable_set_{ProjectEntity.ProjectIndex} set cablesetname='{SetName}' WHERE cablesetid ='{keyValue}'; ");
                _cableSetRepository.AsTenant().CommitTran();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion

    }
}
